package com.cup.bddm.util;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

public class MD5Util {

	private final static Logger logger = Logger.getLogger(MD5Util.class);

	public static String MD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			logger.error("MD5 not support : " + e);
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];
		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	public static byte[] getMD5Mac(byte[] bySourceByte) {
		byte[] byDisByte;
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			md.reset();
			md.update(bySourceByte);
			byDisByte = md.digest();
		} catch (NoSuchAlgorithmException n) {

			return (null);
		}
		return (byDisByte);
	}

	public static String bintoascii(byte[] bySourceByte)

	{
		int len, i;
		byte tb;
		char high, tmp, low;
		String result = new String();
		len = bySourceByte.length;
		for (i = 0; i < len; i++) {
			tb = bySourceByte[i];
			tmp = (char) ((tb >>> 4) & 0x000f);
			if (tmp >= 10)
				high = (char) ('a' + tmp - 10);
			else
				high = (char) ('0' + tmp);
			result += high;
			tmp = (char) (tb & 0x000f);
			if (tmp >= 10)
				low = (char) ('a' + tmp - 10);
			else
				low = (char) ('0' + tmp);
			result += low;
		}
		return result;
	}

	public static String getMD5ofStr(String inbuf) {
		if (inbuf == null || "".equals(inbuf))
			return "";
		return bintoascii(getMD5Mac(inbuf.getBytes()));
	}

	/**
	 * 该方法用于生成签名，参数inbuf=签名种子+xml字符串
	 * 
	 * @param inbuf
	 * @return
	 */
	public static String getSign(String inbuf) {
		return getMD5ofStr(inbuf).toLowerCase();
	}

	// 测试代码
	public static void main(String[] args) {

		String s = new String("123456");
		System.out.println("original string :" + s);
		System.out.println("after md5 :" + MD5(s));
		BigDecimal b = new BigDecimal(s);
		System.out.println(b.toString());

	}
}
